package com.dbapp.imglib.camer;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;
import com.dbapp.imglib.inter.OnTakeCameraListener;
import java.io.File;
import java.util.List;

/**
 * 拍照，摄像头
 */
public class JZCameraActivity extends Activity {
  private String str_img_path;
  public static final String IMAGEFILEPATH_save_sate = "save_sate";

  private static OnTakeCameraListener l;

  public static void start(Context context, String imgPath, OnTakeCameraListener listener) {
    l = listener;
    Intent starter = new Intent(context, JZCameraActivity.class);
    starter.putExtra(JZCameraActivity.IMAGE_PATH_Key, imgPath);
    context.startActivity(starter);
  }

  /**
   * 回调图片地址
   */
  public final static String IMAGE_PATH_Key = "image_path_key";
  static Activity mContext;
  public final static int GET_IMAGE_REQ = 5000;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    str_img_path = getIntent().getStringExtra(IMAGE_PATH_Key);

    // 判断 activity被销毁后 有没有数据被保存下来
    if (savedInstanceState != null) {
      str_img_path = savedInstanceState.getString(IMAGEFILEPATH_save_sate);
    }

    mContext = this;
    if (savedInstanceState == null) {
      initialUI();
    }
  }

  /**
   * 最终传递图片操作
   */
  private void onPanDuanFile() {
    File mFile = new File(str_img_path);
    if (mFile.exists()) {
      if (l != null) {
        l.OnCapture(mFile);
      }
      if (!isScreenChange()) {
        finish();
      }
    } else {
      Toast.makeText(this, "图片获取失败！", Toast.LENGTH_SHORT).show();
    }
  }

  /**
   * 初始化照相机
   */
  public void initialUI() {
    if (ExistSDCard()) {
      showCamera(CreateFiles(str_img_path));
    } else {
      this.finish();
      Toast.makeText(this, "请检查SD卡是否插好！", Toast.LENGTH_SHORT).show();
    }
  }

  /**
   * 相机设置
   */
  private void showCamera(File imgFile) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    //intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out)); // set

    Uri imgUri = null;

    if (Build.VERSION.SDK_INT >= 24) {
      //如果是7.0或以上，使用getUriForFile()获取文件的Uri

      String str_Pagkage_name = getAppProcessName(getApplicationContext());

      //imgUri = FileProvider.getUriForFile(this, "com.smart.safenotice" + ".fileprovider", imgFile);
      imgUri = FileProvider.getUriForFile(this, str_Pagkage_name + ".fileprovider", imgFile);
    } else {
      imgUri = Uri.fromFile(imgFile);
    }

    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri); // set

    startActivityForResult(intent, GET_IMAGE_REQ);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (GET_IMAGE_REQ == requestCode && resultCode == Activity.RESULT_OK) {
      onPanDuanFile();
    } else {
      this.finish();
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString(IMAGEFILEPATH_save_sate, str_img_path + "");
    Log.e("------Bundle outState-----Activity中保存数据：图片路径：", str_img_path + "--");
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // newConfig.orientation获得当前屏幕状态是横向或者竖向
    // Configuration.ORIENTATION_PORTRAIT 表示竖向
    // Configuration.ORIENTATION_LANDSCAPE 表示横屏
    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
      onPanDuanFile();
    }
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
    }
  }

  @Override
  protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
  }

  /**
   * 判断屏幕，横竖屏操作
   */
  @SuppressWarnings("static-access")
  public boolean isScreenChange() {
    Configuration mConfiguration = this.getResources().getConfiguration(); // 获取设置的配置信息
    int ori = mConfiguration.orientation; // 获取屏幕方向

    if (ori == mConfiguration.ORIENTATION_LANDSCAPE) {

      // 横屏
      return true;
    } else if (ori == mConfiguration.ORIENTATION_PORTRAIT) {

      // 竖屏
      return false;
    }
    return false;
  }

  /**
   * http://blog.csdn.net/true100/article/details/51028468
   * 获取当前应用程序的包名
   *
   * @param context 上下文对象
   * @return 返回包名
   */
  public static String getAppProcessName(Context context) {
    //当前应用pid
    int pid = android.os.Process.myPid();
    //任务管理类
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    //遍历所有应用
    List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
    for (ActivityManager.RunningAppProcessInfo info : infos) {
      if (info.pid == pid)//得到当前应用
      {
        return info.processName;//返回包名
      }
    }
    return "";
  }

  /**
   * 判断是否有SD卡
   *
   * @return true 有，false 没有
   */
  public static boolean ExistSDCard() {
    if (android.os.Environment.getExternalStorageState()
        .equals(android.os.Environment.MEDIA_MOUNTED)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 创建文件对象
   *
   * @param path 文件绝对路径
   * @return 返回该文件 file
   */
  public static File CreateFiles(String path) {
    File file = new File(path);
    if (!file.getParentFile().exists()) {
      file.getParentFile().mkdirs(); // 创建文件夹
    }
    return file;
  }
}
